<template>
  <div class="container">
    <el-row class="section">
      <el-col class="section-toolbar">
        <date-range-picker
          v-model="datePicker1"
          type="daterange"
          align="right"
          size="small"
          class="w-240"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="timeChange"/>
        <el-select v-model="listQuery.newsType" size="small" class="w-150">
          <el-option :value="null" label="全部资讯类型"/>
          <el-option v-for="(item,key) in newsTypeOpt" :key="key" :label="key" :value="item"/>
        </el-select>
        <el-select v-model="listQuery.sourceType" size="small" class="w-150">
          <el-option :value="null" label="全部资讯来源"/>
          <el-option v-for="(item,key) in newsSourceOpt" :key="key" :label="key" :value="item"/>
        </el-select>
        <el-button type="primary" icon="el-icon-search" size="small" @click="search()">搜索</el-button>
      </el-col>
    </el-row>
    <div class="show"/>
    <el-row class="p-t-15">
      <el-col>
        <el-tabs ref="tabs" v-model="activeName" type="card">
          <!-- 资讯阅读量uv -->
          <el-tab-pane label="资讯阅读量uv" name="first">
            <el-card class="box-card">
              <div class="title">
                <p>资讯阅读量uv（条）</p>
                <div class="btn">
                  <el-button class="fr m-l-10" size="small" @click="toExport('readUV')">导出
                  </el-button>
                </div>
              </div>
              <div class="echart">
                <div id="readUV" :style="{width: '100%', height: '380px'}"/>
              </div>
            </el-card>
          </el-tab-pane>
          <!-- 资讯阅读量pv -->
          <el-tab-pane label="资讯阅读量pv" name="second">
            <el-card class="box-card">
              <div class="title">
                <p>资讯阅读量pv（条）</p>
                <div class="btn">
                  <el-button class="fr m-l-10" size="small" @click="toExport('readPV')">导出
                  </el-button>
                </div>
              </div>
              <div class="echart">
                <div id="readPV" :style="{width: echartWidth, height: '380px'}"/>
              </div>
            </el-card>
          </el-tab-pane>
          <!-- 人均阅读资讯数 -->
          <el-tab-pane label="人均阅读资讯数" name="third">
            <el-card class="box-card">
              <div class="title">
                <p>人均阅读资讯数（条）</p>
                <div class="btn">
                  <el-button class="fr m-l-10" size="small" @click="toExport('peopleReadCount')">导出
                  </el-button>
                </div>
              </div>
              <div class="echart">
                <div id="peopleReadCount" :style="{width: echartWidth, height: '380px'}"/>
              </div>
            </el-card>
          </el-tab-pane>
          <!-- 人均资讯阅读时长 -->
          <el-tab-pane label="人均资讯阅读时长" name="four">
            <el-card class="box-card">
              <div class="title">
                <p> 人均资讯阅读时长（s）</p>
                <div class="btn">
                  <el-button class="fr m-l-10" size="small" @click="toExport('peopleReadTime')">导出
                  </el-button>
                </div>
              </div>
              <div class="echart">
                <div id="peopleReadTime" :style="{width: echartWidth, height: '380px'}"/>
              </div>
            </el-card>
          </el-tab-pane>
          <!-- 篇均资讯阅读时长 -->
          <el-tab-pane label="篇均资讯阅读时长" name="five">
            <el-card class="box-card">
              <div class="title">
                <p>篇均资讯阅读时长（s）</p>
                <div class="btn">
                  <el-button class="fr m-l-10" size="small" @click="toExport('artileReadTime')">导出
                  </el-button>
                </div>
              </div>
              <div class="echart">
                <div id="artileReadTime" :style="{width: echartWidth, height: '380px'}"/>
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import echarts from 'echarts';
import {
  dateShortcutKeyJS
} from '@/mixins/index.js';
import timeUtils from '@/utils/timeHandle.js';
import {
  exportJsonToExcel,
  formatJson
} from '@/utils/excel/Export2Excel';
import {
  readUvApi,
  readPvApi,
  readPeruserApi,
  readtimePeruserApi,
  readtimepernewsApi
} from '@/api/information-content-analysis.js';
import '@/assets/css/common/style.scss';
const HeadWithOutWeek = {
  readUV: [{
    prop: 'date',
    label: '时间'
  },
  {
    prop: 'km',
    label: '柬文资讯阅读量uv'
  },
  {
    prop: 'zh',
    label: '中文资讯阅读量uv'
  }
  ],
  readPV: [{
    prop: 'date',
    label: '时间'
  },
  {
    prop: 'km',
    label: '柬文资讯阅读量pv'
  },
  {
    prop: 'zh',
    label: '中文资讯阅读量pv'
  }
  ],
  peopleReadCount: [{
    prop: 'date',
    label: '时间'
  },
  {
    prop: 'km',
    label: '柬文人均阅读资讯数'
  },
  {
    prop: 'zh',
    label: '中文人均阅读资讯数'
  }
  ],
  peopleReadTime: [{
    prop: 'date',
    label: '时间'
  },
  {
    prop: 'km',
    label: '柬文人均资讯阅读时长(s)'
  },
  {
    prop: 'zh',
    label: '中文人均资讯阅读时长(s)'
  }
  ],
  artileReadTime: [{
    prop: 'date',
    label: '时间'
  },
  {
    prop: 'km',
    label: '柬文篇均资讯阅读时长(s)'
  },
  {
    prop: 'zh',
    label: '中文篇均资讯阅读时长(s)'
  }
  ]
};
export default {
  mixins: [dateShortcutKeyJS],
  data() {
    return {
      tableName: {
        readUV: '资讯阅读量uv',
        readPV: '资讯阅读量pv',
        peopleReadCount: '人均阅读资讯数',
        peopleReadTime: '人均资讯阅读时长',
        artileReadTime: '篇均资讯阅读时长'
      },
      tableHead: HeadWithOutWeek,
      activeName: 'first',
      newsTypeOpt: {
        '图文': 1,
        '图集': 2,
        '视频': 3,
        '微头条': 5,
        '小视频': 8
      },
      newsSourceOpt: {
        '后台': 2,
        '爬虫': 1,
        '自媒体': 3
      },
      datePicker1: [
        timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24 * 6, 'date'),
        timeUtils.timeHandle(new Date().getTime(), 'date')
      ],
      listQuery: {
        newsType: null,
        sourceType: null,
        beginDate: timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24 * 6, 'date'),
        endDate: timeUtils.timeHandle(new Date().getTime(), 'date'),
        time: 'day' // day, week, month
      },
      xData1: [], // 保存资讯阅读量uvx轴数据
      xData2: [], // 保存资讯阅读量pvx轴数据
      xData3: [], // 保存人均阅读资讯数x轴数据
      xData4: [], // 保存人均资讯阅读时长x轴数据
      xData5: [], // 保存篇均资讯阅读时长x轴数据
      legend: {
        1: ['柬文', '中文'],
        2: ['柬文', '中文'],
        3: ['柬文', '中文'],
        4: ['柬文', '中文'],
        5: ['柬文', '中文']
      },
      list: {
        'readUVKm': [], // 资讯阅读量uv柬文
        'readUVZh': [], // 资讯阅读量uv中文
        'readPVKm': [], // 资讯阅读量pv柬文
        'readPVZh': [], // 资讯阅读量pv中文
        'peopleReadCountZh': [], // 人均阅读资讯数中文
        'peopleReadCountKm': [], // 人均阅读资讯数柬文
        'peopleReadTimeZh': [], // 人均资讯阅读时长中文
        'peopleReadTimeKm': [], // 人均资讯阅读时长柬文
        'artileReadTimeZh': [], // 篇均资讯阅读时长中文
        'artileReadTimeKm': [] // 篇均资讯阅读时长柬文
      },
      exportData: { // 导出表格数据
        'readUV': [], // 资讯阅读量uv
        'readPV': [], // 资讯阅读量pv
        'peopleReadCount': [], // 人均阅读资讯数
        'peopleReadTime': [], // 人均资讯阅读时长
        'artileReadTime': [] // 篇均资讯阅读时长
      },
      echartWidth: null,
      isFirstRender: true
    };
  },
  mounted() {
    this.search();
    this.getWidth();
  },
  methods: {
    timeChange(time) {
      if (!time) return;
      const startTime = Date.parse(time[0]);
      const endTime = Date.parse(time[1]);
      const Days = Math.floor(Math.abs(endTime - startTime) / (24 * 3600 * 1000));
      if (Days <= 30) {
        this.listQuery.time = 'day';
      } else if (Days > 30 && Days <= 42) {
        this.listQuery.time = 'week';
      } else if (Days > 42) {
        this.listQuery.time = 'month';
      }
    },

    getWidth() {
      this.$nextTick(function() {
        this.echartWidth = this.$refs['tabs'].$el.clientWidth + 'px';
      });
    },
    /* 获取资讯阅读量uv */
    getData1() {
      var myChart = echarts.init(document.getElementById('readUV'));
      myChart.showLoading();

      readUvApi(this.listQuery).then(res => {
        if (res.code == 200) {
          const data = res.data || [];

          this.xData1 = [];
          this.list.readUVKm = [];
          this.list.readUVZh = [];

          this.exportData.readUV = data;
          for (var i = 0; i < data.length; i++) {
            this.xData1.push(data[i].date);
            this.list.readUVKm.push(data[i].km);
            this.list.readUVZh.push(data[i].zh);
          }

          this.updateEchart1();
        }
      });
    },
    /* 柱状图-资讯阅读量uv */
    updateEchart1() {
      var myChart = echarts.init(document.getElementById('readUV'));
      myChart.showLoading();

      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: this.legend[1],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [{
          type: 'category',
          data: this.xData1
        }],
        yAxis: [{
          type: 'value'
        }],
        series: [
          {
            name: '中文',
            type: 'bar',
            stack: '广告',
            data: this.list['readUVZh']
          },
          {
            name: '柬文',
            type: 'bar',
            stack: '广告',
            data: this.list['readUVKm']
          }
        ]
      };

      myChart.setOption(option, true);
      myChart.hideLoading();
    },
    /* 获取资讯阅读量pv */
    getData2() {
      if (!this.isFirstRender) {
        var myChart = echarts.init(document.getElementById('readPV'));
        myChart.showLoading();
      }
      readPvApi(this.listQuery).then(res => {
        if (res.code == 200) {
          const data = res.data || [];

          this.xData2 = [];
          this.list.readPVKm = [];
          this.list.readPVZh = [];

          this.exportData.readPV = data;
          for (var i = 0; i < data.length; i++) {
            this.xData2.push(data[i].date);
            this.list.readPVKm.push(data[i].km);
            this.list.readPVZh.push(data[i].zh);
          }

          this.$nextTick(function() {
            this.updateEchart2();
          });
        }
      });
    },
    /* 柱状图-资讯阅读量pv */
    updateEchart2() {
      var myChart = echarts.init(document.getElementById('readPV'));
      myChart.showLoading();

      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: this.legend[1],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [{
          type: 'category',
          data: this.xData2
        }],
        yAxis: [{
          type: 'value'
        }],
        series: [
          {
            name: '中文',
            type: 'bar',
            stack: '广告',
            data: this.list['readPVZh']
          },
          {
            name: '柬文',
            type: 'bar',
            stack: '广告',
            data: this.list['readPVKm']
          }
        ]
      };

      myChart.setOption(option, true);
      myChart.hideLoading();
      this.isFirstRender = false;
    },
    /* 获取人均阅读资讯数 */
    getData3() {
      if (!this.isFirstRender) {
        var myChart = echarts.init(document.getElementById('peopleReadCount'));
        myChart.showLoading();
      }
      readPeruserApi(this.listQuery).then(res => {
        if (res.code == 200) {
          const data = res.data || [];

          this.xData3 = [];
          this.list.peopleReadCountZh = [];
          this.list.peopleReadCountKm = [];

          for (var i = 0; i < data.length; i++) {
            this.xData3.push(data[i].date);
            data[i].zh = Math.round(data[i].zh);
            data[i].km = Math.round(data[i].km);
            this.list.peopleReadCountZh.push(data[i].zh);
            this.list.peopleReadCountKm.push(data[i].km);
          }
          this.exportData.peopleReadCount = data;
          this.$nextTick(function() {
            this.updateEchart3();
          });
        }
      });
    },
    /*  折线图-人均阅读资讯数  */
    updateEchart3() {
      var myChart = echarts.init(document.getElementById('peopleReadCount'));
      myChart.showLoading();
      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {
        },
        legend: {
          data: this.legend[3],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            type: 'category',
            data: this.xData3, // x轴数据
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            min: 0,
            max: Math.ceil(Math.max(...this.list.peopleReadCountZh)) >= Math.ceil(Math.max(...this.list.peopleReadCountKm)) ? Math.ceil(Math.max(...this.list.peopleReadCountZh)) : Math.ceil(Math.max(...this.list.peopleReadCountKm)),
            interval: Math.ceil(Math.max(...this.list.peopleReadCountZh) / 5) >= Math.ceil(Math.max(...this.list.peopleReadCountKm) / 5) ? Math.ceil(Math.max(...this.list.peopleReadCountZh) / 5) : Math.ceil(Math.max(...this.list.peopleReadCountKm) / 5),
            axisLabel: {
              formatter: '{value}'
            }
          }
          // {
          //     type: 'value',
          //     min: 0,
          //     max: Math.ceil(Math.max(...this.list.peopleReadCountKm)),
          //     interval: Math.ceil(Math.max(...this.list.peopleReadCountKm) / 5),
          //     axisLabel: {
          //         formatter: '{value}'
          //     }
          // }
        ],
        series: [{
          name: '中文',
          type: 'line',
          data: this.list.peopleReadCountZh
        }, {

          name: '柬文',
          type: 'line',
          data: this.list.peopleReadCountKm
          // yAxisIndex: 1,
        }]
      };
      myChart.setOption(option, true);
      myChart.hideLoading();
    },
    /* 获取人均资讯阅读时长 */
    getData4() {
      if (!this.isFirstRender) {
        var myChart = echarts.init(document.getElementById('peopleReadTime'));
        myChart.showLoading();
      }
      readtimePeruserApi(this.listQuery).then(res => {
        if (res.code == 200) {
          const data = res.data || [];

          this.xData4 = [];
          this.list.peopleReadTimeZh = [];
          this.list.peopleReadTimeKm = [];

          for (var i = 0; i < data.length; i++) {
            this.xData4.push(data[i].date);
            data[i].zh = Math.round(data[i].zh);
            data[i].km = Math.round(data[i].km);
            this.list.peopleReadTimeZh.push(data[i].zh);
            this.list.peopleReadTimeKm.push(data[i].km);
          }
          this.exportData.peopleReadTime = data;
          this.$nextTick(function() {
            this.updateEchart4();
          });
        }
      });
    },
    /*  折线图-人均资讯阅读时长  */
    updateEchart4() {
      var myChart = echarts.init(document.getElementById('peopleReadTime'));
      myChart.showLoading();
      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {
        },
        legend: {
          data: this.legend[4],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            type: 'category',
            data: this.xData4, // x轴数据
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            min: 0,
            max: Math.ceil(Math.max(...this.list.peopleReadTimeZh)) >= Math.ceil(Math.max(...this.list.peopleReadTimeKm)) ? Math.ceil(Math.max(...this.list.peopleReadTimeZh)) : Math.ceil(Math.max(...this.list.peopleReadTimeKm)),
            interval: Math.ceil(Math.max(...this.list.peopleReadTimeZh) / 5) >= Math.ceil(Math.max(...this.list.peopleReadTimeKm) / 5) ? Math.ceil(Math.max(...this.list.peopleReadTimeZh) / 5) : Math.ceil(Math.max(...this.list.peopleReadTimeKm) / 5),
            axisLabel: {
              formatter: '{value}'
            }
          }
          // {
          //     type: 'value',
          //     min: 0,
          //     max: Math.ceil(Math.max(...this.list.peopleReadTimeKm)),
          //     interval: Math.ceil(Math.max(...this.list.peopleReadTimeKm) / 5),
          //     axisLabel: {
          //         formatter: '{value}'
          //     }
          // }
        ],
        series: [{
          name: '中文',
          type: 'line',
          data: this.list.peopleReadTimeZh
        }, {

          name: '柬文',
          type: 'line',
          data: this.list.peopleReadTimeKm
          // yAxisIndex: 1,
        }]
      };
      myChart.setOption(option, true);
      myChart.hideLoading();
    },
    /* 获取篇均资讯阅读时长 */
    getData5() {
      if (!this.isFirstRender) {
        var myChart = echarts.init(document.getElementById('artileReadTime'));
        myChart.showLoading();
      }
      readtimepernewsApi(this.listQuery).then(res => {
        if (res.code == 200) {
          const data = res.data || [];

          this.xData5 = [];
          this.list.artileReadTimeZh = [];
          this.list.artileReadTimeKm = [];

          for (var i = 0; i < data.length; i++) {
            this.xData5.push(data[i].date);
            data[i].zh = Math.round(data[i].zh);
            data[i].km = Math.round(data[i].km);
            this.list.artileReadTimeZh.push(data[i].zh);
            this.list.artileReadTimeKm.push(data[i].km);
          }
          this.exportData.artileReadTime = data;

          this.$nextTick(function() {
            this.updateEchart5();
          });
        }
      });
    },
    /*  折线图-篇均资讯阅读时长  */
    updateEchart5() {
      var myChart = echarts.init(document.getElementById('artileReadTime'));
      myChart.showLoading();
      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {
        },
        legend: {
          data: this.legend[5],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            type: 'category',
            data: this.xData5, // x轴数据
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            min: 0,
            max: Math.ceil(Math.max(...this.list.artileReadTimeZh)) >= Math.ceil(Math.max(...this.list.artileReadTimeKm)) ? Math.ceil(Math.max(...this.list.artileReadTimeZh)) : Math.ceil(Math.max(...this.list.artileReadTimeKm)),
            interval: Math.ceil(Math.max(...this.list.artileReadTimeZh) / 5) >= Math.ceil(Math.max(...this.list.artileReadTimeKm) / 5) ? Math.ceil(Math.max(...this.list.artileReadTimeZh) / 5) : Math.ceil(Math.max(...this.list.artileReadTimeKm) / 5),
            axisLabel: {
              formatter: '{value}'
            }
          }
          // {
          //     type: 'value',
          //     min: 0,
          //     max: Math.ceil(Math.max(...this.list.artileReadTimeKm)),
          //     interval: Math.ceil(Math.max(...this.list.artileReadTimeKm) / 5),
          //     axisLabel: {
          //         formatter: '{value}'
          //     }
          // }
        ],
        series: [{
          name: '中文',
          type: 'line',
          data: this.list.artileReadTimeZh
        }, {

          name: '柬文',
          type: 'line',
          data: this.list.artileReadTimeKm
          // yAxisIndex: 1,
        }]
      };
      myChart.setOption(option, true);
      myChart.hideLoading();
    },

    /* 搜索 */
    search() {
      if (!this.datePicker1) {
        this.$message.warning('请输入搜索时间', true);
        return;
      }
      this.listQuery.beginDate = this.datePicker1[0];
      this.listQuery.endDate = this.datePicker1[1];
      // this.activeName = 'first'
      this.getData1();
      this.getData2();
      this.getData3();
      this.getData4();
      this.getData5();
    },

    toExport(exportName) {
      const exprtTime = timeUtils.timeHandle(new Date().getTime(), 'date');
      const tHeader = this.tableHead[exportName].map(item => item.label);
      const tKey = this.tableHead[exportName].map(item => item.prop);
      const data = formatJson(tKey, this.exportData[exportName]); // 数据格式化
      const fileName = this.tableName[exportName] + exprtTime;
      exportJsonToExcel(tHeader, data, fileName); // 导出文件
    }
  }
};
</script>
<style lang="scss" scoped>
  .w-150 {
    width: 150px;
  }

  .title {
    height: 32px;
    position: relative;

    p {
      font-size: 22px;
      line-height: 32px;
      text-align: center;
    }

    .btn {
      width: 400px;
      height: 32px;
      position: absolute;
      right: 0;
      top: 0;
    }
  }
</style>
